package com.wj.facedetect.util;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by tangkun on 2018/4/4.
 */

public class CameraUtil {
    public static final String PHOTO_NAME = "wj_dd";

    /**
     * 生成拍照需要的uri(适用于所有版本)
     *
     * @return
     */
    public static Uri buildPhotoUri(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return buildPhotoUriMoreThanN(context);
        } else {
            return buildPhotoUriLessThanN();
        }
    }

    /**
     * 请求访问ConetntProvider的读写权限
     *
     * @param context
     * @param intent
     * @param uri
     */
    public static void grantPermission(Context context, Intent intent, Uri uri) {
        List<ResolveInfo> resolveInfos = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo resolveInfo : resolveInfos) {
            String packagName = resolveInfo.activityInfo.packageName;
            context.grantUriPermission(packagName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }
    }

    /**
     * 处理拍照返回的图片(含压缩、旋转调整)
     * 默认按720*960分辨率来压缩
     *
     * @param context
     * @param uri
     * @return
     */
    public static Bitmap handlePhotoByDecodeAndRotate(Context context, String uri) {
        return handlePhotoByDecodeAndRotate(context, 720, 960, uri);
    }

    /**
     * 处理拍照返回的图片(含压缩、旋转调整)
     *
     * @param context
     * @param reqWidth
     * @param reqHeight
     * @param uri
     * @return
     */
    public static Bitmap handlePhotoByDecodeAndRotate(Context context, int reqWidth, int reqHeight, String uri) {
        String path = uri;
        Bitmap bitmap = null;
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            try {
//                bitmap = BitmapFactory.decodeStream(context.getContentResolver().openInputStream(uri));
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//            }
//        } else {
        bitmap = BitmapFactory.decodeFile(path);
        //}
        if (bitmap != null) {
            int imageDegree = ImageUtil.getImageDegree(path);
            //压缩图片
            Bitmap resultBitmap = ImageUtil.decodeSampledBitmap(bitmap, reqWidth, reqHeight, imageDegree);
            if (resultBitmap != bitmap && !bitmap.isRecycled()) {
                bitmap.recycle();
            }
            return resultBitmap;
        } else {
            return bitmap;
        }
    }

    /**
     * 处理拍照返回的图片(含压缩、旋转调整)
     *
     * @param context
     * @param reqWidth
     * @param reqHeight
     * @param uri
     * @return
     */
    public static Bitmap handlePhotoByDecodeAndRotateUri(Context context, int reqWidth, int reqHeight, Uri uri) {
        String path = FileUtil.getFilePath(uri);
        Bitmap bitmap = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            try {
                bitmap = BitmapFactory.decodeStream(context.getContentResolver().openInputStream(uri));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        } else {
            bitmap = BitmapFactory.decodeFile(path);
        }
        if (bitmap != null) {
            int imageDegree = ImageUtil.getImageDegree(path);
            //压缩图片
            Bitmap resultBitmap = ImageUtil.decodeSampledBitmap(bitmap, reqWidth, reqHeight, imageDegree);
            if (resultBitmap != bitmap && !bitmap.isRecycled()) {
                bitmap.recycle();
            }
            return resultBitmap;
        } else {
            return bitmap;
        }
    }

    /**
     * 根据url获取图片路径
     *
     * @param context
     * @param uri
     * @return
     */
    private static String getPath(Context context, Uri uri) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return getFinalImagePath(context, uri, null);
        } else {
            return uri.getPath();
        }
    }

    private static String getFinalImagePath(Context context, Uri uri, String selection) {
        String path = null;
        Cursor cursor = context.getApplicationContext().getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
//                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                if (index > -1) {
                    path = cursor.getString(index);
                }
            }
            cursor.close();
        }
        return path;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private static String getPathMoreThanN(Context context, Uri uri) {
        //content://com.wj.facedetect.fileprovider/external_files/IMG_20180416_204711.jpg
        String imagePath = null;
        if (DocumentsContract.isDocumentUri(context, uri)) {
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getFinalImagePath(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"),
                        Long.valueOf(docId));
                imagePath = getFinalImagePath(context, contentUri, null);
            }
//        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
        } else if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
            imagePath = getFinalImagePath(context, uri, null);
        }
        return imagePath;
    }

    /**
     * android N 以下版本适用
     *
     * @return
     */
    private static Uri buildPhotoUriLessThanN() {
        File mediaFile = buildPhotoFile();
        if (mediaFile == null) {
            return null;
        }
        return Uri.fromFile(mediaFile);
    }

    /**
     * android N 以上版本适用
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private static Uri buildPhotoUriMoreThanN(Context context) {
        File mediaFile = buildPhotoFile();
        if (mediaFile == null) {
            return null;
        }
        Uri uri /*= FileProvider.getUriForFile(context.getApplicationContext(), context.getPackageName() + ".fileprovider", mediaFile)*/;
        ContentValues contentValues = new ContentValues(1);
        contentValues.put(MediaStore.Images.ImageColumns.DATA, mediaFile.getAbsolutePath());
        uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
        return uri;
    }

    /**
     * 生成拍照文件
     *
     * @return
     */
    private static File buildPhotoFile() {
        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), PHOTO_NAME);
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }
        //创建Media File
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
        return mediaFile;
    }
}
